package com.cn.demo.controller;

import com.cn.demo.config.SeckillRRateLimiter;
import com.cn.demo.entity.SeckillGoods;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试
 *
 * @author wangjf
 * @version 1.0
 * @createDate 2019/10/31 10:27
 * @projectName test
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private RedissonClient redisson;
    @Autowired
    private SeckillRRateLimiter seckillRRateLimiter;

    @GetMapping()
    public String get() {
        return "hello world";
    }

    @PostMapping("rateLimiter")
    public String rateLimiter() {
        if (seckillRRateLimiter.tryAcquire()) {
            seckillRRateLimiter.acquire();
            System.out.println("处理中....");
            return "成功";
        }
        System.out.println("已经达到最大并发,请稍后再试....");
        return "失败";
    }


    /**
     * 秒杀
     *
     * @param
     * @return java.lang.String
     * @author: wangjf
     * @createTime: 2019/11/14 10:25
     */
    @PostMapping("/kill")
    public String seckill() {

        //判断秒杀是否到活动时间，未到时间则不允许秒杀
        //做接口限流，每次进入只能是100个并发，通过atomic进行控制
        //判断用户是否已经秒杀成功，如果成功则返回页面跳转中
        RQueue<SeckillGoods> seckillQueue = redisson.getQueue("seckillQueue");
        SeckillGoods poll = seckillQueue.poll();
        if (poll == null) {
            //未抢购成功者放入一个过期hashMap中，如果在该hashMap则直接返回，不进行任何判断（减缓系统压力）
            System.out.println("秒杀结束");
            return "抱歉，秒杀活动已结束";
        }
        RList<SeckillGoods> seckillList = redisson.getList("seckillList");
        poll.setLockUserId(System.currentTimeMillis() + "");
        seckillList.add(poll);
        System.out.println(poll);
        return poll.getId();
    }


}
